package com.example.demo.commom.timer;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2024-05-15
 * Time:9:29
 */
public class MyTimer {
    private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    private Object locker = new Object();
    public MyTimer() {
        Thread t = new Thread(()->{
            while (true){
                try {
                    synchronized (locker){
                        MyTask task = queue.take();
                        long curtime = System.currentTimeMillis();
                        if(curtime >= task.getTime()){
                            task.getRunnable().run();
                        } else {
                            queue.put(task);
                            locker.wait(task.getTime() - curtime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
    public void schedule(Runnable runnable, long time) throws InterruptedException {
        MyTask task = new MyTask(runnable, time);
        queue.put(task);
        synchronized (locker){
            locker.notify();
;        }
    }
}
